package com.eunion.core.common.jpa;

import java.util.Optional;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.Fetch;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Join;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

/**
 * 
 * @author hallwong
 */
public class JpaUtil {

    public static Optional<Join<?, ?>> getFetchOrJoin(String attribute, From<?, ?> from) {
        for (Fetch<?, ?> f : from.getFetches()) {
            boolean sameName = f.getAttribute().getName().equals(attribute);
            if (sameName) {
                return Optional.of((Join<?, ?>) f);
            }
        }
        for (Join<?, ?> j : from.getJoins()) {
            boolean sameName = j.getAttribute().getName().equals(attribute);
            if (sameName) {
                return Optional.of(j);
            }
        }
        return Optional.empty();
    }

    /**
     * 
     * @param query
     * @param pageable
     * @param total
     * @return
     * @deprecated 未来将使用{@linkplain ProjectionQueryExecutor ProjectionQueryExecutor}接口逐步替代此功能类
     */
    @Deprecated
    public static <T> Page<T> page(TypedQuery<T> query, Pageable pageable, Number total) {
        query.setFirstResult(pageable.getOffset());
        query.setMaxResults(pageable.getPageSize());
        return new PageImpl<>(query.getResultList(), pageable, total.longValue());
    }

}
